<template>
  <div class="app-container">
    <earthquakeImpactField :geomList="geomList" @selectLonLat="selectLonLat" />
    <el-card class="modelChange">
      <el-radio-group v-model="radio" class="ml-4" @change="changeType">
        <el-radio label="1">选择烈度衰减关系模型</el-radio>
        <el-radio label="2">手工填写地震影响场长短轴长度</el-radio>
        <el-radio label="3">导入地震影响场</el-radio>
      </el-radio-group>
    </el-card>
    <el-card v-if="radio == '1' && initDataStatus == true" class="modelDataSelect">
      <el-row>
        <el-col :span="10" :lg="10" :xl="8">
          <Card :data="intensityData" :isEdit="isEdit" type="1"></Card>
        </el-col>
      </el-row>
      <p>请输入经纬度，或者地图点击获取</p>
      <el-form ref="casualtiesRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="longitude" label="经度">
              <el-input v-model="form.longitude" placeholder="经度" style="width:100px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="latitude" label="纬度">
              <el-input v-model="form.latitude" placeholder="纬度" style="width:100px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="magnitude" label="震级">
              <el-input v-model="form.magnitude" placeholder="震级" style="width:100px" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="direction" label="长轴方向">
              <el-input v-model="form.direction" placeholder="方向" style="width:100px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-button type="primary" @click="createInfluenceField">生成地震影响场</el-button>
      </el-form>
    </el-card>
    <el-card v-if="radio == '2'" class="modelDataSelect">
      <el-form :model="mercalliScale" :rules="mercalliScaleRules" style="margin:20px 10px 0 0">
        <el-row>
          <el-col>
            <el-form-item label="震中烈度：" prop="select">
              <el-select v-model="mercalliScale.select" placeholder="请选择" @change="mercalliScaleChange">
                <el-option v-for="(key, val) in optionCode.mercalliScale" :key="key" :label="key" :value="val">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label=" " prop="list">
              <el-table :data="mercalliScale.list" :border="true" stripe>
                <el-table-column label="烈度" align="center" prop="intensity" width="100" />
                <el-table-column label="长轴长度（公里）" align="center" prop="longAxis">
                  <template #default="{ row }">
                    <el-input type="text" v-model="row.longAxis" />
                  </template>
                </el-table-column>
                <el-table-column label="短轴长度（公里）" align="center" prop="shortAxis">
                  <template #default="{ row }">
                    <el-input type="text" v-model="row.shortAxis" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="casualtiesRef" :model="form" :rules="rules">
        <p>请输入经纬度，或者地图点击获取</p>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="longitude" label="经度">
              <el-input v-model="form.longitude" placeholder="经度" style="width:100px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="latitude" label="纬度">
              <el-input v-model="form.latitude" placeholder="纬度" style="width:120px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="magnitude" label="震级">
              <el-input v-model="form.magnitude" placeholder="震级" style="width:100px" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="direction" label="长轴方向">
              <el-input v-model="form.direction" placeholder="方向" style="width:100px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-button type="primary" @click="createInfluenceField">生成地震影响场</el-button>
      </el-form>
    </el-card>
    <el-card v-if="radio == '3'" class="modelDataSelect">
      <p>
        <el-popover placement="right" trigger="click" width="500px" @show="getFieldsDesc">
          <template #reference>
            <el-link :underline="false" type="primary">文件导入字段说明：请使用【CGCS2000】坐标系，标准公里格网。</el-link>
          </template>
          <el-table :data="gridData" v-loading="fieldLoading" stripe>
            <el-table-column width="55" label="序号" type="index" align="center" />
            <el-table-column property="name" label="数据名称" align="center" />
            <el-table-column property="type" label="数据类型" align="center" />
            <el-table-column property="required" label="是否必填" align="center" />
            <el-table-column property="example" label="示例" align="center" />
          </el-table>
        </el-popover>
      </p>
      
      <input type="file" @change="uploadFileChange" style="width: 70px;" id="spaceData-button-selectfile"
        multiple="multiple" accept=".shp,.dbf,.prj,.sbn,.sbx,.shp.xml,.shx,.cpg" />
      <div class="new-filesTextArea" style="margin: 10px 0;min-width: 300px;">
        <el-input type="textarea" :rows="8" placeholder="导入多个文件时，文件名须相同" v-model="textarea" readonly></el-input>
      </div>
      <div class="new-uploadBtnDiv">
        <el-button @click="uploadFileClick" type="primary">上传</el-button>
      </div>
    </el-card>
    <el-card style="position: absolute;bottom: 10px;left: 20px;z-index:2;">
      <el-checkbox v-model="checked1" label="数据列表" size="large" @change="selectDataTable" />
    </el-card>
    <div v-if="checked1" style="background-color: #fff;position: absolute;z-index: 1;right:20px;top:10px;width: 49%;">
      <el-table :data="casualtiesList">
        <el-table-column label="地震影响场编号" align="center" prop="versionCode" />
        <el-table-column label="经度" align="center" prop="longitude" />
        <el-table-column label="纬度" align="center" prop="latitude" />
        <el-table-column label="震级" align="center" prop="earthquakeLevel" />
        <el-table-column label="长轴方向" align="center" prop="direction" />
        <el-table-column label="创建人" align="center" prop="assessUserName" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="text" @click="handleSelect(scope.row.versionCode)">查看</el-button>
            <el-button type="text" @click="handleDelete(scope.row.versionCode)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
        @pagination="getList" />
    </div>
  </div>
</template>
<script setup name="earthquakeImpactField">
import earthquakeImpactField from '@/map/basicDataManage/earthquakeImpactField/indexMap.vue'
import { upLoadFile } from "@/api/system/attachFile";
import Card from './Components/Card.vue'
import { getById, countInfluenceField, countSettingSeismicProcess, importShp, getAll, getInfluencefliedById, deleteInfluencefliedById } from '@/api/basicDataManage/earthquakeImpactField.js'
import { ref } from 'vue';

const { proxy } = getCurrentInstance();
// 保留六位小数
const positive4decimals = (rule, value, callback) => {
  value = String(value)
  if (isNaN(value) || !value) {
    return callback(new Error());
  }
  // var re = /^([0-9]+[\d]*(.[0-9]{6}))$/;
  var re = /^[-]{0,1}(([1-9]{1}[0-9]{0,8})|([0]{1}))((\.{1}[0-9]{1,6}$)|$)/;
  if (!re.test(value)) {
    callback(new Error());
  } else {
    callback();
  }
}
// 保留一位小数
const positiveInteger = (rule, value, callback) => {
  value = String(value)
  if (isNaN(value) || !value) {
    return callback(new Error());
  }
  var re = /^([0-9]+[\d]*(.[0-9]{1}))$/;
  if (!re.test(value)) {
    callback(new Error());
  } else {
    callback();
  }
}
// 保留一位小数且不超过180
const positiveInteger1 = (rule, value, callback) => {
  value = String(value);
  if (isNaN(value) || !value) {
    return callback(new Error('请输入有效的数字'));
  }
  var re = /^(180(\.0)?|[1-9][0-9]?(\.[0-9])?|1[0-7][0-9](\.[0-9])?)$/;
  if (!re.test(value)) {
    callback(new Error('请输入0到180之间的数字，可保留一位小数'));
  } else {
    callback();
  }
}
const checkList = (rule, value, callback) => {
  let isFull = value.every(item => {
    return item.longAxis != '' && item.shortAxis != ''
  })
  if (isFull) {
    callback()
  } else {
    callback(new Error("请将地震影响场长短轴长度填写完整!"))
  }
}
const mercalliScaleRules = reactive({
  // select: [{ required: true, message: '请选择震中烈度', trigger: 'change' }],
  list: [{ validator: checkList }]
})
const casualtiesList = ref([])
const checked1 = ref('')
const modelData = reactive({
  intensityData: {},
  form: {
    direction: '',
    longitude: '',
    latitude: '',
    magnitude: ''
  },
  rules: {
    direction: [
      { required: true, trigger: "blur", validator: positiveInteger1 }
    ],
    longitude: [
      { required: true, message: "保留六位小数", trigger: "blur", validator: positive4decimals }
    ],
    latitude: [
      { required: true, message: "保留六位小数", trigger: "blur", validator: positive4decimals }
    ],
    magnitude: [
      { required: true, message: "保留一位小数", trigger: "blur", validator: positiveInteger }
    ],
  },
  queryParams: {
    page: 1,
    rows: 10
  }
})
let { intensityData, form, rules, queryParams } = toRefs(modelData);
const textarea = ref("");//上传文件只读显示文本框
const radio = ref('1')
const isEdit = ref(false)
const initDataStatus = ref(false)
const optionCode = reactive({
  'mercalliScale': { 'Ⅹ': 'Ⅹ', 'Ⅸ': 'Ⅸ', 'Ⅷ': 'Ⅷ', 'Ⅶ': 'Ⅶ', 'Ⅵ': 'Ⅵ' },
})
// 生成地震影响场
let mercalliScaleOrigin = [
  { intensity: 'Ⅹ', longAxis: '', shortAxis: '' },
  { intensity: 'Ⅸ', longAxis: '', shortAxis: '' },
  { intensity: 'Ⅷ', longAxis: '', shortAxis: '' },
  { intensity: 'Ⅶ', longAxis: '', shortAxis: '' },
  { intensity: 'Ⅵ', longAxis: '', shortAxis: '' }
]
const mercalliScale = reactive({
  select: 'Ⅹ',
  list: mercalliScaleOrigin
})
// 生成地震影响场-震中烈度切换
const mercalliScaleChange = (val) => {
  mercalliScaleOrigin = mercalliScaleOrigin.map(item => {
    return {
      intensity: item.intensity,
      longAxis: '',
      shortAxis: ''
    }
  })
  mercalliScale.list = mercalliScaleOrigin.slice(0)
  let index = mercalliScale.list.findIndex(item => item.intensity == val)
  mercalliScale.list.splice(0, index)
}
const selectLonLat = (coord) => {
  if (radio.value == '1' || radio.value == '2') {
    form.value.longitude = coord[0].toFixed(6)
    form.value.latitude = coord[1].toFixed(6)
  }
}
provide('modelData', modelData)
function changeType() {

}
const geomList = ref([])
function createInfluenceField() {
  if (radio.value == '1') {
    let data = form.value
    data.id = intensityData.value.id
    countInfluenceField(data).then(res => {
      geomList.value = res.data
    }).catch()
  } else if (radio.value == '2') {
    let data = {}
    data.id = intensityData.value.id
    data.epicenterIntensity = mercalliScale.select
    mercalliScale.list.map(item => {
      switch (item.intensity) {
        case 'Ⅹ':
          data.longLength5 = item.longAxis
          data.shortLength5 = item.shortAxis
          break
        case 'Ⅸ':
          data.longLength4 = item.longAxis
          data.shortLength4 = item.shortAxis
          break
        case 'Ⅷ':
          data.longLength3 = item.longAxis
          data.shortLength3 = item.shortAxis
          break
        case 'Ⅶ':
          data.longLength2 = item.longAxis
          data.shortLength2 = item.shortAxis
          break
        case 'Ⅵ':
          data.longLength1 = item.longAxis
          data.shortLength1 = item.shortAxis
          break
      }
    })
    data.direction = form.value.direction,
      data.longitude = form.value.longitude,
      data.latitude = form.value.latitude,
      data.magnitude = form.value.magnitude
    countSettingSeismicProcess(data).then(res => {
      geomList.value = res.data
    }).catch()
  }
}
const minList = ref([])
const nameList = ref([])
//选择文件
function uploadFileChange() {
  let uploadinputFiles = document.getElementById("spaceData-button-selectfile").files;
  minList.value = [];
  nameList.value = [];
  let text = "";
  for (let i = 0; i < uploadinputFiles.length; i++) {
    text += uploadinputFiles[i].name + "\n";
    // 获取这个文件的后缀名
    minList.value.push(uploadinputFiles[i].name.slice(uploadinputFiles[i].name.length - 3, uploadinputFiles[i].name.length));
    nameList.value.push(uploadinputFiles[i].name.split(".")[0]);
  }
  textarea.value = text;
}
function getList() {
  getAll(queryParams.value).then(res => {
    casualtiesList.value = res.data.rows
    total.value = res.data.total
  }).catch()
}
const total = ref(0)
function selectDataTable(value, flag) {
  if (value) {
    getAll(queryParams.value).then(res => {
      casualtiesList.value = res.data.rows
      total.value = res.data.total
    }).catch()
  }
}
//警告消息
function alertMsg(msg) {
  proxy.$modal.msgWarning(msg);
}
//上传文件
function uploadFileClick() {
  let uploadinput = document.getElementById("spaceData-button-selectfile");
  if (!judgeIsOnce(minList.value)) {
    alertMsg('上传数量限制:.dbf、.prj、.shp、.shx、.cpg文件各1个;.sbn、.sbx、.shp.xml文件至多一个。');
    return;
  }
  if (!judgeName(nameList.value)) {
    alertMsg("文件名请保持一致！");
    return;
  }
  const fileFormData = new FormData();
  for (let i = 0; i < uploadinput.files.length; i++) {
    fileFormData.append('file', uploadinput.files[i]);
  }
  let fileIds = "";//上传附件id列表
  //上传文件到附件表
  upLoadFile(fileFormData).then(res => {
    // console.log("上传文件成功")
    if (res.code == 200) {
      let resultArr = res.data;
      for (let i = 0; i < resultArr.length; i++) {
        if (i > 0) {
          fileIds += ",";
        }
        fileIds += resultArr[i].attachId;
      }
      importShp({ attachIds: fileIds }).then((response) => {
        geomList.value = response.data
      }).catch(err => {
        // loading.value = false;
      });
    }
  });
}
function handleSelect(id) {
  getInfluencefliedById({ versionCode: id }).then(res => {
    geomList.value = res.data
  }).catch()
}
function handleDelete(id) {
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return deleteInfluencefliedById({ versionCode: id })
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });

}
//校验Shp文件类型
function judgeIsOnce(list) {
  // ["dbf","prj","shp","shx","cpg"];
  let dbf = 0, prj = 0, shp = 0, shx = 0, cpg = 0, sbn = 0, sbx = 0, xml = 0;
  for (let i = 0; i < list.length; i++) {
    let item = list[i];
    if (item == 'dbf') dbf++;
    if (item == 'prj') prj++;
    if (item == 'shp') shp++;
    if (item == 'shx') shx++;
    if (item == 'cpg') cpg++;
    if (item == 'sbn') sbn++;
    if (item == 'sbx') sbx++;
    if (item == 'xml') xml++;
  }
  if (dbf == 1 && prj == 1 && shp == 1 && shx == 1 && cpg == 1 && sbn < 2 && sbx < 2 && xml < 2) return true;
  else return false;
}
//校验Shp文件名称
function judgeName(list) {
  let name = list[0];
  let result = list.filter(function (item) {
    return item == name;
  })
  if (result.length == list.length) return true;
  else return false;
}
function selectFoundationData() {
  getById({ id: '04c1557e8abd4e5e80ea9f28f5621df0' }).then(res => {
    intensityData.value = res.data
    initDataStatus.value = true
  }).catch()
}
const gridData = ref([])
const fieldLoading = ref(false)
const getFieldsDesc = () => {
  fieldLoading.value = true
  gridData.value = [
    { "name": "PGA", "type": "浮点型", "required": "否", "example": "0.10792571828" },
    { "name": "PGV", "type": "浮点型", "required": "否", "example": "0.010026525409" },
    { "name": "PGV_vs30", "type": "浮点型", "required": "否", "example": "0.0076093997977" },
    { "name": "intensity", "type": "文本", "required": "是", "example": "Ⅶ" },
  ]
  fieldLoading.value = false
}

onMounted(() => {
  setTimeout(() => {
    selectFoundationData()
  }, 200)
})

</script>
<style scoped lang="scss">
.mapDiv {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 80%;
}

.modelChange {
  position: absolute;
  top: 20px;
  left: 20px;
}

.modelDataSelect {
  position: absolute;
  top: 95px;
  left: 20px;
}
</style>